package com.rd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.dto.LoginFormDTO;
import com.rd.dto.Result;
import com.rd.dto.UserDTO;
import com.rd.entity.User;
import com.rd.entity.UserInfo;
import com.rd.mapper.UserMapper;
import com.rd.service.UserInfoService;
import com.rd.service.UserService;
import com.rd.utils.RedisConstants;
import com.rd.utils.RegexUtils;
import com.rd.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.rd.utils.RedisConstants.USER_SIGN_KEY;
import static com.rd.utils.SystemConstants.USER_NICK_NAME_PREFIX;

//ServiceImpl<M extends BaseMapper<T>, T>
// Mapper接口要继承BaseMapper<T>
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserInfoService userInfoService;

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();
//        if (!RegexUtils.isPhoneInvalid(phone)) {
//            return Result.fail("手机号格式错误");
//        }
//        String phone1 = (String) session.getAttribute("phone");
//        if (!phone.equals(phone1)){
//            return Result.fail("手机号不一致");
//        }
        String code = loginForm.getCode();

//        Object cacheCode = session.getAttribute("code");
        //从缓存中获取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+phone);

        if (cacheCode == null || !cacheCode.equals(code)){
            return Result.fail("验证码错误");
        }
        // 查询数据库
        User user = query().eq("phone", phone).one();
        //用户不存在，新建用户
        if (user == null){
            user = createUserWithPhone(phone);
        }

        //TODO 基于token登录
        //随机生成token
        String token = UUID.randomUUID().toString(true);
        //user对象的属性复制到userDTO对象
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将userDTO转换成Map
        Map<String, String> userMap1 = new HashMap<>();
        //stringRedisTemplate的key和value都是String,而id是long类型的所以要转换成string
        userMap1.put("id", userDTO.getId().toString());
        userMap1.put("nickName",userDTO.getNickName());
        userMap1.put("icon", userDTO.getIcon());
        //保存到redis
        String key = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(key,userMap1);
        //设置用户token过期时间
        stringRedisTemplate.expire(key,1,TimeUnit.HOURS);

//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //登录成功后，删除验证码缓存
        stringRedisTemplate.delete(phone);

        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }

    @Override
    public Result sedCode(String phone, HttpSession session) {

        System.out.println("sendCode");
//        // 校验手机号
//        if (!RegexUtils.isPhoneInvalid(phone)){
//            return Result.fail("手机号格式错误");
//        }
        // 生成6位验证码
        String code = RandomUtil.randomNumbers(6);
        System.out.println("code:"+code);

        session.setAttribute("phone", phone);

        //将验证码放入缓存并设置过期时间
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone, code, 300, TimeUnit.SECONDS);
//        session.setAttribute("code",code);
        //返回ok
        return Result.ok(code);
    }

    // 用户签到
    @Override
    public Result sign() {

        // 获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        // key后缀
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //拼接key
        String key =USER_SIGN_KEY + userId + keySuffix;
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();

        System.out.println("day:"+ dayOfMonth);
        // 写入 redis
        // bitmap key offset 1(true)
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    //连续签到天数
    @Override
    public Result signCount() {
        // 获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        // key后缀
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //拼接key
        String key =USER_SIGN_KEY + userId + keySuffix;
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();

        //获取本月至今的所有签到记录，返回的是十进制数
        List<Long> res = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0));
        if (res == null || res.isEmpty()) {
            return Result.ok(0);
        }
        System.out.println("for");
        for (Long l : res) {
            System.out.println(l);
        }
        Long num = res.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        int count = 0;
        //遍历
        while (true){
            // num 与 1相与，得到最后一个bit位
            if ((num & 1) == 0){  //判断最后一个bit位是否为0,为0说明未签到
                break;
            }else {
                count++;  // 不为0说明已签到，计数器 +1
            }
            num >>>= 1;  // num右移一位,去掉最后一位bit,继续下一位bit
        }
        return Result.ok(count);
    }

    @GetMapping("/me")
    public Result me(){
        // 获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();

        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }
}
